<template>
  <Dialog v-model="dialogVisible" title="批量处理" width="900px">
    <div v-loading="formLoading">
      <el-form
        ref="formRef"
        :model="formData"
        label-width="120px"
      >
        <el-form-item label="处理类型" prop="processType">
          <el-radio-group v-model="formData.processType" @change="handleProcessTypeChange">
            <el-radio label="批量审核">批量审核</el-radio>
            <el-radio label="批量分配">批量分配</el-radio>
            <el-radio label="批量通知">批量通知</el-radio>
            <el-radio label="批量状态变更">批量状态变更</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="选择对象">
          <div class="selection-area">
            <div class="filter-bar">
              <el-input
                v-model="filterText"
                placeholder="搜索申请人姓名或身份证号"
                style="width: 300px; margin-right: 10px;"
                clearable
              />
              <el-select
                v-model="filterStatus"
                placeholder="筛选状态"
                style="width: 150px; margin-right: 10px;"
                clearable
              >
                <el-option label="待审核" value="待审核" />
                <el-option label="审核中" value="审核中" />
                <el-option label="已通过" value="已通过" />
                <el-option label="已拒绝" value="已拒绝" />
              </el-select>
              <el-button @click="loadCandidateList">查询</el-button>
            </div>
            
            <el-table
              ref="tableRef"
              :data="filteredCandidateList"
              @selection-change="handleSelectionChange"
              max-height="300"
              border
            >
              <el-table-column type="selection" width="55" />
              <el-table-column prop="candidateName" label="申请人" width="100" />
              <el-table-column prop="idCard" label="身份证号" width="180" />
              <el-table-column prop="professionName" label="申报职业" width="150" />
              <el-table-column prop="skillLevel" label="技能等级" width="120" />
              <el-table-column prop="currentStatus" label="当前状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="getStatusType(row.currentStatus)">
                    {{ row.currentStatus }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="submitTime" label="提交时间" width="150" />
            </el-table>
            
            <div class="selection-summary">
              已选择 {{ selectedCandidates.length }} 项
              <el-button type="text" @click="selectAll">全选</el-button>
              <el-button type="text" @click="clearSelection">清空</el-button>
            </div>
          </div>
        </el-form-item>
        
        <!-- 批量审核配置 -->
        <template v-if="formData.processType === '批量审核'">
          <el-form-item label="审核结果" prop="auditResult">
            <el-radio-group v-model="formData.auditResult">
              <el-radio label="通过">审核通过</el-radio>
              <el-radio label="拒绝">审核拒绝</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item label="审核意见" prop="auditComments">
            <el-input
              v-model="formData.auditComments"
              type="textarea"
              :rows="3"
              placeholder="请输入审核意见"
            />
          </el-form-item>
        </template>
        
        <!-- 批量分配配置 -->
        <template v-if="formData.processType === '批量分配'">
          <el-form-item label="分配给" prop="assigneeId">
            <el-select
              v-model="formData.assigneeId"
              placeholder="请选择处理人员"
              style="width: 100%"
            >
              <el-option
                v-for="user in userList"
                :key="user.id"
                :label="user.nickname"
                :value="user.id"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="分配说明">
            <el-input
              v-model="formData.assignComments"
              type="textarea"
              :rows="3"
              placeholder="请输入分配说明"
            />
          </el-form-item>
        </template>
        
        <!-- 批量通知配置 -->
        <template v-if="formData.processType === '批量通知'">
          <el-form-item label="通知类型" prop="notificationType">
            <el-select
              v-model="formData.notificationType"
              placeholder="请选择通知类型"
              style="width: 100%"
            >
              <el-option label="短信通知" value="SMS" />
              <el-option label="邮件通知" value="EMAIL" />
              <el-option label="系统消息" value="SYSTEM" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="通知内容" prop="notificationContent">
            <el-input
              v-model="formData.notificationContent"
              type="textarea"
              :rows="4"
              placeholder="请输入通知内容"
            />
          </el-form-item>
        </template>
        
        <!-- 批量状态变更配置 -->
        <template v-if="formData.processType === '批量状态变更'">
          <el-form-item label="目标状态" prop="targetStatus">
            <el-select
              v-model="formData.targetStatus"
              placeholder="请选择目标状态"
              style="width: 100%"
            >
              <el-option label="待审核" value="待审核" />
              <el-option label="审核中" value="审核中" />
              <el-option label="已通过" value="已通过" />
              <el-option label="已拒绝" value="已拒绝" />
              <el-option label="已撤回" value="已撤回" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="变更原因" prop="changeReason">
            <el-input
              v-model="formData.changeReason"
              type="textarea"
              :rows="3"
              placeholder="请输入状态变更原因"
            />
          </el-form-item>
        </template>
      </el-form>
    </div>
    
    <template #footer>
      <el-button 
        @click="submitBatchProcess" 
        type="primary" 
        :disabled="formLoading || selectedCandidates.length === 0"
      >
        执行批量处理 ({{ selectedCandidates.length }})
      </el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

defineOptions({ name: 'BatchProcess' })

const emit = defineEmits(['success'])

const dialogVisible = ref(false)
const formLoading = ref(false)
const formRef = ref()
const tableRef = ref()
const filterText = ref('')
const filterStatus = ref('')
const candidateList = ref([])
const selectedCandidates = ref([])
const userList = ref([])

const formData = reactive({
  processType: '批量审核',
  auditResult: '',
  auditComments: '',
  assigneeId: undefined,
  assignComments: '',
  notificationType: '',
  notificationContent: '',
  targetStatus: '',
  changeReason: ''
})

const filteredCandidateList = computed(() => {
  let list = candidateList.value
  
  if (filterText.value) {
    list = list.filter(item => 
      item.candidateName.includes(filterText.value) || 
      item.idCard.includes(filterText.value)
    )
  }
  
  if (filterStatus.value) {
    list = list.filter(item => item.currentStatus === filterStatus.value)
  }
  
  return list
})

/** 打开弹窗 */
const open = async () => {
  dialogVisible.value = true
  await loadCandidateList()
  await loadUserList()
  resetForm()
}

/** 加载候选人列表 */
const loadCandidateList = async () => {
  try {
    // TODO: 调用获取候选人列表的API
    candidateList.value = []
  } catch (error) {
    console.error('加载候选人列表失败:', error)
  }
}

/** 加载用户列表 */
const loadUserList = async () => {
  try {
    // TODO: 调用获取用户列表的API
    userList.value = []
  } catch (error) {
    console.error('加载用户列表失败:', error)
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.processType = '批量审核'
  formData.auditResult = ''
  formData.auditComments = ''
  formData.assigneeId = undefined
  formData.assignComments = ''
  formData.notificationType = ''
  formData.notificationContent = ''
  formData.targetStatus = ''
  formData.changeReason = ''
  
  selectedCandidates.value = []
  filterText.value = ''
  filterStatus.value = ''
}

/** 处理类型变更 */
const handleProcessTypeChange = () => {
  // 清空相关字段
  Object.keys(formData).forEach(key => {
    if (key !== 'processType') {
      formData[key] = ''
    }
  })
}

/** 选择变更处理 */
const handleSelectionChange = (selection: any[]) => {
  selectedCandidates.value = selection
}

/** 全选 */
const selectAll = () => {
  tableRef.value?.toggleAllSelection()
}

/** 清空选择 */
const clearSelection = () => {
  tableRef.value?.clearSelection()
}

/** 获取状态类型 */
const getStatusType = (status: string) => {
  const statusMap = {
    '待审核': 'warning',
    '审核中': 'primary',
    '已通过': 'success',
    '已拒绝': 'danger'
  }
  return statusMap[status] || 'info'
}

/** 提交批量处理 */
const submitBatchProcess = async () => {
  if (selectedCandidates.value.length === 0) {
    ElMessage.error('请选择要处理的对象')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确认对选中的 ${selectedCandidates.value.length} 项执行${formData.processType}操作吗？`,
      '确认批量处理',
      { type: 'warning' }
    )
    
    formLoading.value = true
    
    const processData = {
      processType: formData.processType,
      candidateIds: selectedCandidates.value.map(item => item.id),
      ...formData
    }
    
    // TODO: 调用批量处理的API
    // await batchProcessWorkflow(processData)
    
    ElMessage.success('批量处理执行成功')
    dialogVisible.value = false
    emit('success')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量处理失败:', error)
      ElMessage.error('批量处理失败')
    }
  } finally {
    formLoading.value = false
  }
}

defineExpose({ open })
</script>

<style scoped>
.selection-area {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 15px;
}

.filter-bar {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.selection-summary {
  margin-top: 10px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
